package com.xbjtech.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbjtech.model.MobileYzm;
import com.xbjtech.model.User;
import com.xbjtech.service.MobileYzmService;
import com.xbjtech.service.UserService;
import com.xbjtech.shiro.MobileYzmToken;

public class MobileYzmRealm extends AuthorizingRealm  {

	@Autowired
	UserService userService;
	
	@Autowired
	MobileYzmService mobileYzmService;
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("MobileYzmRealm.doGetAuthenticationInfo()");
		MobileYzmToken myToken = null;
		if (!(token instanceof MobileYzmToken)) {
			throw new AuthenticationException("登录信息有误");
		}
		myToken = (MobileYzmToken) token;
		String mobile = myToken.getPrincipal().toString();
		User user = userService.selectUserByMobile(mobile);
		if (user == null) {
			// 用户不存在
			throw new UnknownAccountException("用户名不存在");
		}
		MobileYzm yzm = mobileYzmService.selectMobileYzmByMobile(mobile);
		if (null == yzm) {
			throw new AuthenticationException("验证码过时");
		}
		return new SimpleAuthenticationInfo(user, yzm.getYzm(), getName());
	}

}
